const mysql = require("mysql2/promise");
const logger = require("../utils/logger");

// 创建数据库连接池
const pool = mysql.createPool({
  socketPath: "/tmp/mysql.sock",
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    logger.info("数据库连接成功");
    connection.release();
    return true;
  } catch (error) {
    logger.error(`数据库连接失败: ${error.message}`, { error: error.stack });
    return false;
  }
}

module.exports = {
  pool,
  testConnection,
};
